/**
 * Created by moko1988 on 15/12/1.
 */
define([
    'backbone',
    'models/business/list',
    'text!templets/business/list.html',
    'text!templets/business/newList.html',
    'text!templets/business/newList-change.html',
    'utils/dataTableUtil',
    'utils/urlUtil',
    'jquerypage',
    'select2',
    'moment'
], function(
    BackBone,
    Model,
    Tpl,
    ModalAdd,
    ModalAddCh,
    DataTable,
    UrlUtil
) {
    var view = Backbone.View.extend({
        el: '#CONTENT',
        events: {
            'click [role=add]': 'addFun', //添加资源
            'click [role=edit]': 'editFun', //修改资源
            'click [role=del]': 'delFun', //删除资源
            'click [role=save]': 'saveFun',
            'click [role=saveChange]': 'saveFunCh',
            'change #pageSize': 'changePageSize', //选择分页宽度
            'click [role=rank]': 'rank', //排序
            'click [role=review]': 'review', //审核
            'click [role=recommend]': 'recommend', //推荐
            'click #checkAll': 'checkAll', //全选、取消
            'click input[name=idarr]': 'checkItem', //选择、取消单条记录
            'change #ad_category': 'changeListCategory_ad',
            'change #game_category': 'changeListCategory_game'
        },
        /*初始化*/
        initialize: function() {
            $(this.el).html(Tpl);
            $(this.el).off();
            this.page = '1';
            this.listRows = '10';
            this.idArr = [];
            this.categoryid = '';
            $('#pageSize').select2();
            this.renderCategory_ad();
            // this.renderCategory_game();
            // this.fetchCategory_game();
        } ,
        // renderCategory: function(){
        //     var opts = '<option>选择类别</option>';
        //         opts += '<option value="1">已结算</option>';
        //         opts += '<option value="0">未结算</option>';
        //     $('#list-category').html(opts).prop('disabled',false).select2();
        //     this.render();
        // },
        renderCategory_ad: function(){
            var _this = this;
            Model.fetchCategory_ad({
                type: 'get',
                success: function(map) {
                    //console.log(map);
                    var opts = '<option value="">选择类别</option>',
                        category = {};
                    _.each(map, function(o){
                        category[o.id] = o;
                        opts += '<option value="'+o.id+'">'+ o.contacts_name+'</option>';
                    });
                    _this.categoryOpts = opts;
                    _this.categoryObj = category;
                    $('#ad_category').html(opts).prop('disabled',false).select2();
                    // $('#game_category').html(opts).prop('disabled',false).select2();
                    $('[role=add]').prop('disabled',false);
                    _this.render();
                }
            })
        },

        //  renderCategory_game: function(){
        //     var _this = this;
        //     s
        //     Model.fetchCategory_game({
        //         type: 'get',
        //         success: function(map) {
        //             //console.log(map);
        //             var opts = '<option value="">选择类别</option>',
        //                 category = {};
        //             _.each(map, function(o){
        //                 category[o.id] = o;
        //                 opts += '<option value="'+o.id+'">'+ o.game_name+'</option>';
        //             });
        //             _this.categoryOpts = opts;
        //             _this.categoryObj = category;
        //             // $('#ad_category').html(opts).prop('disabled',false).select2();
        //             $('#game_category').html(opts).prop('disabled',false).select2();
        //             $('[role=add]').prop('disabled',false);
        //             _this.render();
        //         }
        //     })
        // },

        changeListCategory_ad: function(e){
            // alert('1');
            var _this = this;
            var $target = $(e.currentTarget),
                sign = $target.val();
                // console.log(sign);
            this.categoryid = sign;
            Model.search({
                
                type: 'post',
                data: {
                    user_id: sign ,
                    page: this.page,
                    page_size: this.listRows
                },
                // success: function(map) {
                //     console.log(map);
                //     _this.render();
                //     // alert('1');
                // }
                success: function(map) {
                    var data = map.list,
                        page = map.page,

                        count = data.length;
                    _this.pageTotal = page.total_page;
                    _.each(data,function(o, i){

                        var rank_up = '<button class="btn" role="rank" data-type="1" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn" role="rank" data-type="0" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        if(_this.categoryid == ''){

                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        }else{

                            if (_this.page == 1 && i == 0) {

                                rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                            }
                            if (_this.page == _this.pageTotal && i == (count - 1)) {

                                rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                            }
                        }

                        o.checkbox = '<input type="checkbox" value="'+ o.id +'" name="idarr">';
                    
                        if(o.order_time!=''){o.order_time = moment(o.order_time * 1000).format('YYYY-MM-DD HH:mm')}else{o.order_time = ''};
                
                        if(o.notify_downsteam_time!=''){o.notify_downsteam_time = moment(o.notify_downsteam_time * 1000).format('YYYY-MM-DD HH:mm')}else{o.notify_downsteam_time = ''};

                        if(o.order_status == 1){
                            o.order_status = '<font color="red">未支付</font>';
                        }else if(o.order_status == 2){
                            o.order_status = '<font color="green">已支付</font>';
                        }else if(o.order_status == 3){
                            o.order_status = '<font color="green">已通知</font>';
                        }

                    })

                    var tableHead = ['<input type="checkbox" id="checkAll">', '序号', '订单号', '游戏名称', '渠道名称', '分层比例' , '订单金额' , '订单时间',  '通知时间','支付状态'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'id'),
                            _.pluck(data,'order_number'),
                            _.pluck(data,'game_name'),
                            _.pluck(data,'channel_name'),
                            _.pluck(data,'layered'),
                            _.pluck(data,'order_price'),
                            _.pluck(data,'order_time'),
                            // _.pluck(data,'payment_order'),
                            _.pluck(data,'notify_downsteam_time'),
                            _.pluck(data,'order_status')
                        );

                    var swit = function(){
                        console.log(order_status)
                    };

                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });

                    $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });

                }
            })

            // this.render();
        },     


        changeListCategory_game: function(e){
            // alert('1');
            var _this = this;
            var $target = $(e.currentTarget),
                sign = $target.val();
                // console.log(sign);
            this.categoryid = sign;
            Model.search({
                
                type: 'post',
                data: {
                    game_id: sign ,
                    page: this.page,
                    page_size: this.listRows
                },
                // success: function(map) {
                //     console.log(map);
                //     _this.render();
                //     // alert('1');
                // }
                success: function(map) {
                    var data = map.list,
                        page = map.page,

                        count = data.length;
                    _this.pageTotal = page.total_page;
                    _.each(data,function(o, i){

                        var rank_up = '<button class="btn" role="rank" data-type="1" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn" role="rank" data-type="0" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        if(_this.categoryid == ''){

                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        }else{

                            if (_this.page == 1 && i == 0) {

                                rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                            }
                            if (_this.page == _this.pageTotal && i == (count - 1)) {

                                rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                            }
                        }

                        o.checkbox = '<input type="checkbox" value="'+ o.id +'" name="idarr">';
                    
                        if(o.order_time!=''){o.order_time = moment(o.order_time * 1000).format('YYYY-MM-DD HH:mm')}else{o.order_time = ''};
                
                        if(o.notify_downsteam_time!=''){o.notify_downsteam_time = moment(o.notify_downsteam_time * 1000).format('YYYY-MM-DD HH:mm')}else{o.notify_downsteam_time = ''};

                        if(o.order_status == 1){
                            o.order_status = '<font color="red">未支付</font>';
                        }else if(o.order_status == 2){
                            o.order_status = '<font color="green">已支付</font>';
                        }else if(o.order_status == 3){
                            o.order_status = '<font color="green">已通知</font>';
                        }

                    })

                    var tableHead = ['<input type="checkbox" id="checkAll">', '序号', '订单号', '游戏名称', '渠道名称', '分层比例' , '订单金额' , '订单时间',  '通知时间','支付状态'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'id'),
                            _.pluck(data,'order_number'),
                            _.pluck(data,'game_name'),
                            _.pluck(data,'channel_name'),
                            _.pluck(data,'layered'),
                            _.pluck(data,'order_price'),
                            _.pluck(data,'order_time'),
                            // _.pluck(data,'payment_order'),
                            _.pluck(data,'notify_downsteam_time'),
                            _.pluck(data,'order_status')
                        );


                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });

                    $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });

                }
            })

            // this.render();
        },
       
        /*排序*/
        rank: function(e) {
            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                id = $target.attr('data-id'),
                _this = this;
            Model.rank({
                data: {
                    id: id,
                    type: type
                },
                success: function() {
                    jAlert('操作成功！', function() {
                        _this.render();
                    });
                }
            })
        },
        /*全选、取消*/
        checkAll: function(e) {
            var $target = $(e.currentTarget),
                isCheck = $target.prop('checked'),
                _this = this;
            if (isCheck) {
                $('input[name=idarr]').prop('checked', true);
                $('input[name=idarr]').each(function() {
                    _this.idArr.push($(this).val());
                })
            } else {
                $('input[name=idarr]').prop('checked', false);
                this.idArr = [];
            }
        },
        /*选择、取消单条记录*/
        checkItem: function() {
            this.idArr = [];
            var isCheckAll = true,
                _this = this;
            $('input[name=idarr]').each(function() {
                if ($(this).prop('checked')) {
                    _this.idArr.push($(this).val());
                } else {
                    isCheckAll = false;
                }
            })
            if (isCheckAll) {
                $('#checkAll').prop('checked', true);
            } else {
                $('#checkAll').prop('checked', false);
            }
        },
        /*选择分页宽度*/
        changePageSize: function(e) {
            var $target = $(e.currentTarget),
                val = $target.val();
            this.listRows = val;
            this.render();
        },
        /*渲染结果列表*/
        render: function() {
            $('#chart_table_div').html(loading);
            var _this = this;
            Model.fetchList({
                type: 'post',
                data: {
                    // ad_id:1,
                    page: this.page,
                    page_size: this.listRows,
                    //cid: this.categoryid
                },
                success: function(map) {
                    var data = map.list,
                        page = map.page,

                        count = data.length;
                    _this.pageTotal = page.total_page;
                    _.each(data,function(o, i){

                        var rank_up = '<button class="btn" role="rank" data-type="1" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn" role="rank" data-type="0" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        if(_this.categoryid == ''){

                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        }else{

                            if (_this.page == 1 && i == 0) {

                                rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                            }
                            if (_this.page == _this.pageTotal && i == (count - 1)) {

                                rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                            }
                        }

                        o.checkbox = '<input type="checkbox" value="'+ o.id +'" name="idarr">';
                    
                        if(o.sign == 1){
                            o.sign = '<font color="red">封停</font>';
                        }else if(o.sign == 0) {
                            o.sign = '<font color="green">正常</font>';
                        }

                    })

                    var tableHead = ['<input type="checkbox" id="checkAll">', '序号', '名称', '手机号', '状态'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'id'),
                            _.pluck(data,'name'),
                            _.pluck(data,'phone'),
                            _.pluck(data,'sign')
                        );


                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });

                    $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });

                }
            })
        },
        /*分页*/
        pageClick: function(page) {
            var _this = this;
            this.page = page;
            $("#pager").pager({
                pagenumber: this.page,
                pagecount: this.pageTotal,
                buttonClickCallback: function(page){
                    _this.pageClick(page);
                }
            });
            this.render();
        },
       
        addFun: function() {
            // window.location.hash = 'view/article-add'
            $(this.el).append(ModalAdd);
            var $myModal = $('#myModal');
            $myModal.find('h4').html('添加商务');
            $myModal.off();
            $myModal.modal();
            $myModal.on('hidden.bs.modal', function(e) {
                $myModal.remove();
            });
        },

      /*修改*/
        editFun: function(e){
            $(this.el).append(ModalAddCh);
            var $target = $(e.currentTarget),
                $myModal = $('#myModal'),
                id = this.idArr[0],
                _this = this;

           
             if (this.idArr.length) {   
                $myModal.off();
                $myModal.modal();
                $myModal.find('h4').html('修改商务信息');
                $myModal.find('[role=saveChange]').prop('disabled', true);
                // this.uploadifyIni();
                 $('#add-category').prop('disabled',false).html(this.categoryOpts);
                /*弹窗关闭*/
                $myModal.on('hidden.bs.modal', function(e) {
                    $myModal.remove();
                });
                $('#loading').html(loading);
                $('#data-form').hide();
 
                Model.fetchInfo({
                    type:'post',
                    data: {
                        id: id
                    },
                    success: function(map) {
                        $myModal.find('input[name=id]').val(id);
                        $myModal.find('input[name=name]').val(map.name);
                        $myModal.find('input[name=key]').val(map.phone);
                        // $myModal.find('input[name=phone]').val(map.phone);
                        // $myModal.find('input[name=corp]').val(map.corporate_name);
                        // $myModal.find('input[name=name]').val(map.contacts_name);
                        // $myModal.find('input[name=content]').val(map.remarks);
                        // map.litpic != '' && _this.imgEcho($myModal.find('input[name=litpic]'), map.litpic);
    
                        $('#loading').html('');
                        $('#data-form').show();
                        $myModal.find('[role=saveChange]').prop('disabled', false);
                    }
                 })
            } else {
                jAlert('请选择要操作的数据');
            }
        },


        //保存修改
         saveFunCh: function() {
            var _this = this,
                $myModal = $('#myModal'),
                $form = $myModal.find('form[role=form]'),
                subBtn = $myModal.find('button[role=saveChange]'),
                isOK = this.checkForm();
            if (isOK) {
                subBtn.html('正在提交..').prop('disabled', true);

                Model.saveChange({
                    type: 'post',
                    data: $form.serialize(),
                    success: function() {
                        subBtn.html('提 交').prop('disabled', false);
                        jAlert('提交成功', function() {
                            $myModal.modal('hide');
                            _this.render();
                        })
                    }
                })
            }
        },

        //新增
         saveFun: function() {
            var _this = this,
                $myModal = $('#myModal'),
                $form = $myModal.find('form[role=form]'),
                subBtn = $myModal.find('button[role=save]'),
                isOK = this.checkForm();
            if (isOK) {
                subBtn.html('正在提交..').prop('disabled', true);

                Model.save({
                    type:'post',
                    data: $form.serialize(),
                    success: function() {
                        subBtn.html('提 交').prop('disabled', false);
                        jAlert('提交成功', function() {
                            $myModal.modal('hide');
                            _this.render();
                        })
                    }
                })
            }
        },

       

        /*审核*/
        review: function(e){
            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                _this = this;
            if (this.idArr.length) {
                var id = this.idArr.join(',');
                Model.review({
                    type: 'post',
                    data: {
                        id: id,
                        status: type
                    },
                    success: function(map) {
                        jAlert('操作成功！', function() {
                            _this.idArr = [];
                            _this.render();
                        });
                    }
                })
            } else {
                jAlert('请选择要操作的数据');
            }
        },
      
        /*推荐/取消推荐*/
        recommend: function(e){
            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                _this = this;
            if (this.idArr.length) {
                var id = this.idArr.join(',');
                Model.recommend({
                    data: {
                        id: id,
                        type: type
                    },
                    success: function(map) {
                        jAlert('操作成功！', function() {
                            _this.idArr = [];
                            _this.render();
                        });
                    }
                })
            } else {
                jAlert('请选择要操作的数据');
            }
        },
        /*删除*/
        delFun: function(e) {
            var $target = $(e.currentTarget),
                id = $target.parents('tr').attr('data-id'),
                _this = this;
            if (this.idArr.length) {
                var id = this.idArr.join(',');
                jConfirm('确定要删除？', function(s) {
                    if (s) {
                        Model.delete({
                            data: {
                                id: id
                            },
                            success: function(map) {
                                jAlert('删除成功', function() {
                                    _this.idArr = [];
                                    _this.render();
                                })
                            }
                        })
                    }
                })
            } else {
                jAlert('请选择要操作的数据');
            }

        },

       

         checkForm: function() {
            var $form = $('[role=form]'),
                $number = $form.find('input[name=name]'),
                $key = $form.find('input[name=key]'),
              
                getTip = function(e) {
                    var text = e.siblings('label.control-label').html();
                    // text = text.substr(0, text.length - 1);
                    return text;
                },
                errShow = function(e, msg) {
                    var $err = e.siblings('em');
                    $err.html(msg).css("opacity", '1');
                    $err.stop(0, 0).animate({
                        "opacity": 0
                    }, 3500);
                    rest = false;
                },
                rest = true;

                
            if ($.trim($number.val()) == '') {
                errShow($number, '请填写' + getTip($number));
            } else if ($number.val().length < 2 || $number.val().length > 20) {
                errShow($number, '请填写2-20个字符');
            }

            var reg = /^1[3|4|5|7|8][0-9]{9}$/;
            var result = reg.test($key.val());
            if(!result){
                 errShow($key, '请填写正确的手机号格式');
            }
           

            return rest;
        },
    })
    return view;
})